﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Fis.Win.Utils;
using Agile.Engine.Utils;

namespace Fis.Win.Forms
{
    public partial class BillEditForm : BaseForm
    {
        public BillEditForm()
        {
            InitializeComponent();
        }

        DataTable AccountSource = CacheContext.LowerAccountCache();
        bool isInitialize = false;

        public override string Message
        {
            get
            {
                return iMessage.Caption;
            }
            set
            {
                iMessage.Caption = value;
                ShowMessage(value);
            }
        }

        public override void InitializeBinding()
        {
            var m = ViewModel["master"] as DataTable;
            var d = ViewModel["detail"] as DataTable;
            ViewModel["Action"] = ViewState.ToString();
            if (ViewModel.ContainsKey("isInitialize"))
                isInitialize = (bool)ViewModel["isInitialize"];
            else
            {
                isInitialize = m.Rows[0]["FSTATUS"].Equals(4);
                ViewModel["isInitialize"] = isInitialize;
            }
            var range = DataUtils.Parse(1, AppSession.Book["FBOOKRANGE"]);
            UIUtils.ClearBindings(layoutControl1);

            #region Master
            range = (range < 1) ? 1 : (range > 12) ? 12 : range;
            edDate.DataBindings.Add("EditValue", m, "FENTERDATE");
            //最大录入时间，初始化取启用日期的前一天，否则取本年最后一天
            edDate.Properties.MaxValue =
                isInitialize
                ? DateTime.Parse(AppSession.Book["FBOOKSTARTIME"].ToString()).AddMinutes(-1)
                : DateTime.Parse(string.Format("{0}-01-01", AppSession.Year)).AddYears(+1).AddMinutes(-1);
            //最小录入时间，初始化取上年第一天， 否则取本期第一天
            edDate.Properties.MinValue =
                isInitialize
                ? DateTime.Parse(string.Format("{0}-01-01", AppSession.Year)).AddYears(-1)
                : DateTime.Parse(string.Format("{0}-{1}-01", AppSession.Year, range));

            Text = isInitialize ? "初始化录入" : "凭证录入";

            //addnew
            if (ViewState == Agile.Engine.View.ViewState.AddNew)
            {
                //日期初始化
                m.Rows[0]["FENTERDATE"] = BillDateInitialize(range);
                m.Rows[0]["FSTATUS"] = isInitialize ? 4 : 0;
                m.Rows[0]["FENTER"] = AppSession.UserSID;
                //未同步
                m.Rows[0]["FSYNC"] = 0;
            }

            var billtype = CacheContext.GetCache("BILLTYPE");
            UIUtils.LookUpBinding(edKind, billtype, "caption", "key");
            edKind.DataBindings.Add("EditValue", m, "FBILLTYPE");
            edKind.Focus();

            edNumber.DataBindings.Add("EditValue", m, "FNO");
            edSerial.DataBindings.Add("EditValue", m, "FSEQUENCE");
            edRecord.DataBindings.Add("EditValue", m, "FATTACHMENT");

            edAudit.DataBindings.Add("EditValue", m, "FCHECKED");
            edPost.DataBindings.Add("EditValue", m, "FPOST");
            edEnter.DataBindings.Add("EditValue", m, "FENTER");

            UIUtils.LookUpBinding(edAudit, CacheContext.GetCache("TUSER"), "FUSERNAME", "SID");
            UIUtils.LookUpBinding(edPost, CacheContext.GetCache("TUSER"), "FUSERNAME", "SID");
            UIUtils.LookUpBinding(edEnter, CacheContext.GetCache("TUSER"), "FUSERNAME", "SID");
            #endregion

            #region Details
            InitializeAccountEdit(reAccount);

            gridControl1.DataSource = d;
            gridView1.FocusedColumn = colSummary;
            gridView1.FocusedRowHandle = 0;
            d.DefaultView.Sort = string.Empty;
            #endregion
        }

        bool IsLock = false;

        bool ValidateBeforeSave()
        {
            var info = ViewModel["master"] as DataTable;
            //不是自己或者主管不能修改
            if (!AppSession.IsAdminUser && !info.Rows[0]["FENTER"].Equals(AppSession.UserSID))
            {
                Message = "只有主管和制单人可进行修改";
                return false;
            }

            //非初始化状态
            if (((DateTime)edDate.EditValue).Month < int.Parse(AppSession.Range) && !isInitialize)
            {
                Message = "凭证日期不在当前会计期间";
                return false;
            }

            //凭证状态
            if (info.Rows[0]["FCHECKED"] != DBNull.Value)
            {
                Message = "凭证已审核，不可修改";
                return false;
            }

            IsLock = true;
            gridView1.UpdateCurrentRow();
            var target = gridView1.FocusedColumn.VisibleIndex;
            gridView1.FocusedColumn = gridView1.Columns[(target == 0) ? 1 : 0];
            gridView1.FocusedColumn = gridView1.Columns[target];
            gridView1.UpdateTotalSummary();

            Validate();

            var source = (gridControl1.DataSource as DataTable);
            var delete = (from r in source.AsEnumerable()
                          where (StringUtils.IsEmpty(r["FACCOUNTCODE"]))
                          select r).ToList();

            for (var i = 0; i < delete.Count; i++)
            {
                source.Rows.Remove(delete[i]);
            }
            source.AcceptChanges();

            //if (isInitialize)
            //{
            //    IsLock = false;
            //    return true;
            //}

            ///明细行验证
            for (var i = 0; i < gridView1.RowCount; i++)
            {
                var row = gridView1.GetDataRow(i);
                gridView1.FocusedRowHandle = i;


                if (StringUtils.IsEmpty(row["FEXPLANATION"]))
                {
                    Message = "摘要不能为空";
                    gridView1.FocusedColumn = colSummary;
                    IsLock = false;
                    return false;
                }

                if (StringUtils.IsEmpty(row["FACCOUNTCODE"]))
                {
                    //Message = "会计科目不能为空";
                    //gridView1.FocusedColumn = colAccount;
                    //return false;
                    continue;
                }

                var accdata = CacheContext.LowerAccountCache().Select(string.Format("SID='{0}'", row["FACCOUNTCODE"]));
                if (accdata.Length == 0)
                {
                    Message = "无效的会计科目";
                    gridView1.FocusedColumn = colAccount;
                    IsLock = false;
                    return false;
                }

                var debit = Agile.Engine.Utils.DataUtils.Parse(0m, row["FDEBITAMOUNT"]);
                var credit = Agile.Engine.Utils.DataUtils.Parse(0m, row["FCREDITAMOUNT"]);

                if (debit == 0 && credit == 0)
                {
                    Message = "金额必须输入";
                    IsLock = false;
                    return false;
                }

                DataRow data = accdata[0];

                //核算项目
                if (data["FISFZHS"].ToString() != "1")
                {
                    continue;
                }

                //外币核算
                if (data["FWBHS"].ToString() != "0")
                {
                    if (StringUtils.IsEmpty(row["FRATE"]) ||
                        (StringUtils.IsEmpty(row["FCURRENCYDEBIT"]) && StringUtils.IsEmpty(row["FCURRENCYCREDIT"])))
                    {
                        //借方有设为借方，贷方有设为贷方，否则设科目余额方向
                        var direct = (!StringUtils.IsEmpty(row["FDEBITAMOUNT"])) ? 1
                            : ((!StringUtils.IsEmpty(row["FDEBITAMOUNT"])) ? 2 : int.Parse(data["FJD"].ToString()));
                        gridView1.FocusedColumn = (direct == 1) ? colDebit : colCredit;

                        AidsProcess(direct);
                        Message = "请输入外币核算信息";
                        IsLock = false;
                        return false;
                    }
                }

                //数量核算
                if (data["FQUANTITY"].ToString() != "0")
                {
                    if (StringUtils.IsEmpty(row["FUNITPRICE"]) ||
                        (StringUtils.IsEmpty(row["FQUANTITYDEBIT"]) && StringUtils.IsEmpty(row["FCURRENCYCREDIT"])))
                    {
                        //借方有设为借方，贷方有设为贷方，否则设科目余额方向
                        var direct = (!StringUtils.IsEmpty(row["FDEBITAMOUNT"])) ? 1
                            : ((!StringUtils.IsEmpty(row["FDEBITAMOUNT"])) ? 2 : int.Parse(data["FJD"].ToString()));
                        gridView1.FocusedColumn = (direct == 1) ? colDebit : colCredit;
                        AidsProcess(direct);
                        Message = "请输入数量核算信息";
                        IsLock = false;
                        return false;
                    }
                }

                //辅助核算
                if (!StringUtils.IsEmpty(data["FFZHS"]))
                {
                    if (StringUtils.IsEmpty(row["FHSVALUE"]))
                    {
                        //借方有设为借方，贷方有设为贷方，否则设科目余额方向
                        var direct = (!StringUtils.IsEmpty(row["FDEBITAMOUNT"])) ? 1
                            : ((!StringUtils.IsEmpty(row["FDEBITAMOUNT"])) ? 2 : int.Parse(data["FJD"].ToString()));
                        gridView1.FocusedColumn = (direct == 1) ? colDebit : colCredit;
                        AidsProcess(direct);
                        Message = "请输入辅助核算信息";
                        IsLock = false;
                        return false;
                    }
                }

            }

            if (gridView1.RowCount < 2)
            {
                Message = "至少2条分录";
                iAdd_ItemClick(null, null);
                iAdd_ItemClick(null, null);
                IsLock = false;
                return false;
            }

            if (DataUtils.Parse(0m, colDebit.SummaryItem.SummaryValue) -
               DataUtils.Parse(0m, colCredit.SummaryItem.SummaryValue) != 0)
            {
                Message = "借贷金额不平";
                return false;
            }


            IsLock = false;
            return true;
        }

        void InitializeAccountEdit(DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit edit)
        {
            edit.ShowHeader = true;
            edit.Columns.Clear();
            edit.Columns.AddRange(
                new DevExpress.XtraEditors.Controls.LookUpColumnInfo[]{
                     new DevExpress.XtraEditors.Controls.LookUpColumnInfo("FCODE","科目编码")
                    ,new DevExpress.XtraEditors.Controls.LookUpColumnInfo("FNAME","科目名称")
                    ,new DevExpress.XtraEditors.Controls.LookUpColumnInfo("FRATECODE","币种编码")
                    ,new DevExpress.XtraEditors.Controls.LookUpColumnInfo("FRATENAME","币种名称")
                });
            edit.DataSource = AccountSource;
        }

        void AccountEditorSourceFilter(string key)
        {
            var filter = "SID like %{0}% or FNAME like %{0}%";
            AccountSource.DefaultView.RowFilter = string.Format(filter, key);
        }

        #region Events

        private void iAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var d = ViewModel["detail"] as DataTable;
            if (gridView1.FocusedRowHandle < 0)
                d.Rows.Add(d.NewRow());
            else
            {
                d.Rows.InsertAt(d.NewRow(), gridView1.FocusedRowHandle);
            }
        }

        private void iDel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (gridView1.FocusedRowHandle < 0)
                return;

            var row = gridView1.GetFocusedDataRow();
            row.Delete();
            row.Table.AcceptChanges();
            //row.AcceptChanges();

        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (IsLock)
                return;

            IsLock = true;
            var prev = gridView1.GetDataRow(e.PrevFocusedRowHandle);
            var focus = gridView1.GetFocusedDataRow(); //gridView1.GetDataRow(e.FocusedRowHandle);

            if (prev != null && focus != null && Agile.Engine.Utils.StringUtils.IsEmpty(focus["FEXPLANATION"]))
            {
                focus["FEXPLANATION"] = prev["FEXPLANATION"];
            }

            ///最后一行时自动新增行
            if (e.FocusedRowHandle == gridView1.RowCount - 1)
            {
                var d = ViewModel["detail"] as DataTable;
                d.Rows.Add(d.NewRow());
            }
            IsLock = false;
        }

        private void reAccount_Leave(object sender, EventArgs e)
        {
            var focus = gridView1.GetFocusedDataRow();
            if (focus == null)
                return;
            var lastValue = gridView1.GetFocusedDataRow()["FACCOUNTCODE"];
            var newValue = (sender as DevExpress.XtraEditors.BaseEdit).EditValue;
            if (lastValue != newValue)
            {
                var data = gridView1.GetFocusedDataRow();
                data["FACCOUNTCODE"] = newValue;

                //更换科目代码清空辅助信息
                data["FDEBITAMOUNT"] =
                data["FCREDITAMOUNT"] =
                data["FCURRENCYDEBIT"] =
                data["FCURRENCYCREDIT"] =
                data["FQUANTITYDEBIT"] =
                data["FQUANTITYCREDIT"] =
                data["FHSVALUE"] =
                data["FRATE"] =
                data["FUNITPRICE"] = DBNull.Value;
            }
        }

        private void iAmount_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var d = gridView1.GetDataRow(gridView1.FocusedRowHandle);
            //FDEBITAMOUNT	借方金额
            //FCREDITAMOUNT	贷方金额
            //FCURRENCYDEBIT	借方外币金额
            //FCURRENCYCREDIT	贷方外币金额
            //FQUANTITYDEBIT	借方数量
            //FQUANTITYCREDIT	贷方数量
            var debit = Agile.Engine.Utils.DataUtils.Parse(0m, d["FDEBITAMOUNT"]);
            var credit = Agile.Engine.Utils.DataUtils.Parse(0m, d["FCREDITAMOUNT"]);

            //贷方转借方
            if (debit == 0)
            {
                d["FDEBITAMOUNT"] = d["FCREDITAMOUNT"];
                d["FCURRENCYDEBIT"] = d["FCURRENCYCREDIT"];
                d["FQUANTITYDEBIT"] = d["FQUANTITYCREDIT"];
                d["FCREDITAMOUNT"] = DBNull.Value;
                d["FCURRENCYCREDIT"] = DBNull.Value;
                d["FQUANTITYCREDIT"] = DBNull.Value;
            }
            else
            {
                d["FCREDITAMOUNT"] = d["FDEBITAMOUNT"];
                d["FCURRENCYCREDIT"] = d["FCURRENCYDEBIT"];
                d["FQUANTITYCREDIT"] = d["FQUANTITYDEBIT"];
                d["FDEBITAMOUNT"] = DBNull.Value;
                d["FCURRENCYDEBIT"] = DBNull.Value;
                d["FQUANTITYDEBIT"] = DBNull.Value;
            }

            gridView1.UpdateCurrentRow();
        }

        private void reDebit_EditValueChanged(object sender, EventArgs e)
        {
            ClearAmount(1);
            var value = (sender as DevExpress.XtraEditors.BaseEdit).EditValue;
            gridView1.GetFocusedDataRow()["FDEBITAMOUNT"] = (value == null) ? DBNull.Value : value;
        }

        private void reCredit_EditValueChanged(object sender, EventArgs e)
        {
            ClearAmount(2);
            var value = (sender as DevExpress.XtraEditors.BaseEdit).EditValue;
            gridView1.GetFocusedDataRow()["FCREDITAMOUNT"] = (value == null) ? DBNull.Value : value;

        }

        private void reDebit_Leave(object sender, EventArgs e)
        {
            var v = (sender as DevExpress.XtraEditors.BaseEdit).EditValue;
            if (!Agile.Engine.Utils.StringUtils.IsEmpty(v))
                AidsProcess(1);
        }

        private void reCredit_Leave(object sender, EventArgs e)
        {
            var v = (sender as DevExpress.XtraEditors.BaseEdit).EditValue;
            if (!Agile.Engine.Utils.StringUtils.IsEmpty(v))
                AidsProcess(2);
        }

        private void iAccount_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var v = UIManager.ShowEdit<AccountEditForm>("AccountEditViewProvider");
            if (Agile.Engine.Utils.DataUtils.Parse(DialogResult.Cancel, v.ViewResult) == System.Windows.Forms.DialogResult.OK)
            {
                reAccount.DataSource = AccountSource = CacheContext.LowerAccountCache();
            }
        }

        private void iNavigate_ItemCLick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var data = (gridControl1.DataSource as DataTable);
            var rowCount = 0;
            foreach (var d in data.AsEnumerable())
            {
                if (!StringUtils.IsEmpty(d["FACCOUNTCODE"]))
                    rowCount++;
            }

            if (rowCount > 1 && !ViewModel.ContainsKey("isNavigate"))
            {
                if (DialogResult.Yes == DevExpress.XtraEditors.XtraMessageBox.Show(
                "是否保存当前凭证?", "提示信息", MessageBoxButtons.YesNo))
                {
                    //验证失败
                    if (!ValidateBeforeSave())
                    {
                        return;
                    }

                    //保存失败
                    if (!SaveProcess())
                    {
                        return;
                    }
                }
            }

            var filter = decimal.Parse(edSerial.EditValue.ToString());

            switch (e.Item.Name)
            {
                case "iFirst":
                    filter = 1;
                    break;
                case "iPrev":
                    filter = (filter - 1 < 1) ? 1 : --filter;
                    break;
                case "iNext":
                    filter++;
                    break;
                case "iLast":
                    filter = decimal.MaxValue;
                    break;
            }

            ViewModel["filter"] = filter;

            ViewModel["filter1"] = StringUtils.IsEmpty(edDate.EditValue) ? AppSession.Book["FBOOKRANGE"] : ((DateTime)edDate.EditValue).Month;
            ViewModel["isNavigate"] = 1;
            ViewProvider.ViewState = ViewState = Agile.Engine.View.ViewState.Modify;
            ViewModel = ViewProvider.ExecuteQuery(ViewModel);
            InitializeBinding();

        }

        private void iBalance_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (!ValidateAccountValue())
                return;


            var focus = gridView1.GetFocusedDataRow();
            focus["FDEBITAMOUNT"] = focus["FCREDITAMOUNT"] = 0;
            gridView1.UpdateTotalSummary();
            var debit = DataUtils.Parse(0m, colDebit.SummaryItem.SummaryValue);
            var credit = DataUtils.Parse(0m, colCredit.SummaryItem.SummaryValue);

            //FDEBITAMOUNT	借方金额
            //FCREDITAMOUNT	贷方金额
            if (gridView1.FocusedColumn.FieldName == "FDEBITAMOUNT")
            {
                focus["FDEBITAMOUNT"] = credit - debit;
                ClearAmount(1);
            }
            else if (gridView1.FocusedColumn.FieldName == "FCREDITAMOUNT")
            {
                focus["FCREDITAMOUNT"] = debit - credit;
                ClearAmount(2);
            }
            else
            {
                if (credit > debit)
                {
                    focus["FDEBITAMOUNT"] = credit - debit;
                    ClearAmount(1);
                }
                else
                {
                    focus["FCREDITAMOUNT"] = debit - credit;
                    ClearAmount(2);
                }

            }

            gridView1.UpdateCurrentRow();
            gridView1.UpdateTotalSummary();

        }

        private void iSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (!ValidateBeforeSave())
            {
                return;
            }

            if (SaveProcess())
            {
                ViewResult = DialogResult.OK;
                Close();
            }
        }

        private void iSaveNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ValidateBeforeSave())
                SaveNewProcess();

        }


        #endregion

        #region Custom

        /// <summary>
        /// 验证会计科目
        /// </summary>
        /// <returns></returns>
        bool ValidateAccountValue()
        {
            var d = gridView1.GetDataRow(gridView1.FocusedRowHandle);
            var col = gridView1.FocusedColumn;
            if (gridView1.FocusedColumn == colAccount)
            {
                gridView1.FocusedColumn = colSummary;
            }

            if (Agile.Engine.Utils.StringUtils.IsEmpty(d["FACCOUNTCODE"]))
            {
                Message = "请输入会计科目";
                gridView1.FocusedColumn = colAccount;
                return false;
            }

            Message = string.Empty;
            gridView1.FocusedColumn = col;
            return true;
        }

        /// <summary>
        /// 清理金额
        /// </summary>
        /// <param name="field"></param>
        void ClearAmount(int direct)
        {
            var d = gridView1.GetFocusedDataRow();
            if (direct == 1) //jie
            {
                d["FCREDITAMOUNT"] = DBNull.Value;
                d["FCURRENCYCREDIT"] = DBNull.Value;
                d["FQUANTITYCREDIT"] = DBNull.Value;
            }
            else
            {
                d["FDEBITAMOUNT"] = DBNull.Value;
                d["FCURRENCYDEBIT"] = DBNull.Value;
                d["FQUANTITYDEBIT"] = DBNull.Value;
            }
        }

        /// <summary>
        /// 处理辅助核算
        /// </summary>
        /// <param name="direct"></param>
        void AidsProcess(int direct)
        {
            var d = gridView1.GetDataRow(gridView1.FocusedRowHandle);

            var acc = CacheContext.LowerAccountCache();
            var value = d["FACCOUNTCODE"].ToString();

            var data = acc.Select(string.Format("SID='{0}'", value));

            if (data.Length < 1)
                return;

            //核算项目
            if (data[0]["FISFZHS"].ToString() == "1")
            {
                using (var f = new BillExtraForm())
                {
                    f.Account = data[0];
                    f.BillDetail = gridView1.GetDataRow(gridView1.FocusedRowHandle);
                    f.BillDirect = direct;
                    if (DialogResult.OK == f.ShowDialog())
                    {
                        ClearAmount(direct);
                        gridView1.UpdateCurrentRow();
                        gridView1.UpdateTotalSummary();
                    }
                }
            }
        }

        /// <summary>
        /// 日期初始化
        /// </summary>
        /// <param name="range"></param>
        /// <returns></returns>
        DateTime BillDateInitialize(int range)
        {
            DateTime d = DateTime.Now;
            //当前日期在当前期间时取当前日期
            //当前日期大于当前期间时取当前期间最后一天

            if (isInitialize)
            {
                return edDate.Properties.MaxValue;
            }

            if (d.Month > range)
            {
                if (range >= 12)
                    d = DateTime.Parse(string.Format("{0}-1-1", AppSession.Year)).AddYears(1).AddMinutes(-1);
                else
                    d = DateTime.Parse(string.Format("{0}-{1}-1", AppSession.Year, range + 1)).AddMinutes(-1);
            }

            return d;
        }

        protected virtual bool SaveProcess()
        {
            if (ViewModel.Contains("isNavigate"))
                ViewModel.Remove("isNavigate");

            ///失败
            if (!ViewProvider.ExecuteUpdate(ViewModel))
            {
                return false;
            }

            Message = "保存成功";
            ViewModel["Saved"] = 1;
            return true;
        }

        protected virtual void SaveNewProcess() { if (SaveProcess()) InitializeAfterSave(); }

        protected virtual void InitializeAfterSave()
        {
            ViewProvider.ViewState = ViewState = Agile.Engine.View.ViewState.AddNew;
            ViewModel = ViewProvider.InitializeViewModel(ViewModel);
            InitializeBinding();
            if (ViewModel.ContainsKey("Saved"))
                ViewModel.Remove("Saved");
        }

        protected override bool BeforeEscapeClose()
        {
            if (gridControl1.IsFocused)
                return base.BeforeEscapeClose();
            return true;
        }
        #endregion

        private void edDate_EditValueChanged(object sender, EventArgs e)
        {
            if (IsLock || ViewState != Agile.Engine.View.ViewState.AddNew)
                return;

            if (StringUtils.IsEmpty(edDate.EditValue))
                return;

            IsLock = true;
            var m = ViewModel["master"] as DataTable;
            var range = ((DateTime)edDate.EditValue).Month;

            var seq = ((Fis.Win.Rules.BillEditViewProvider)ViewProvider).BillSequnce(range.ToString());
            m.Rows[0]["FENTERDATE"] = edDate.EditValue;
            m.Rows[0]["FNO"] = m.Rows[0]["FSEQUENCE"] = seq;
            IsLock = false;
        }

        private void BillEditForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (ViewModel.ContainsKey("Saved"))
                return;

            if (!BeforeEscapeClose())
            {
                e.Cancel = true;
            }
        }


    }
}
